//
//  ViewController.m
//  JigSaw
//
//  Created by Slim Wang on 15/1/5.
//  Copyright (c) 2015年 LITB. All rights reserved.
//

#import "JSPhotoGroupChooseViewController.h"
#import "JSPhotoChooseViewController.h"
#import "JSModelEditViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "JSPhotoGroupCell.h"
#import "UIColor+Help.h"
#import "JSPreviewManager.h"
#import "JSModelManager.h"


@interface JSPhotoGroupChooseViewController ()<UITableViewDelegate, UITableViewDataSource, ImageAddPreViewDelegate>

@property(nonatomic, weak)IBOutlet UITableView* tableView;

@property(nonatomic, strong) ALAssetsLibrary* assetsLibrary;
@property(nonatomic, strong) NSMutableArray* assetsGroups;
@property(nonatomic, strong) NSMutableArray* groupThumbnails;

@end


@implementation JSPhotoGroupChooseViewController


- (void)setupGroup
{
    if (!self.assetsLibrary)
        self.assetsLibrary = [[ALAssetsLibrary alloc] init];
    
    if (!self.assetsGroups)
        self.assetsGroups = @[].mutableCopy;
    else
        [self.assetsGroups removeAllObjects];
    
    if (!self.groupThumbnails)
        self.groupThumbnails = @[].mutableCopy;
    else
        [self.groupThumbnails removeAllObjects];
    
    ALAssetsLibraryGroupsEnumerationResultsBlock resultsBlock = ^(ALAssetsGroup *group, BOOL *stop) {
        if (group)
        {
            [group setAssetsFilter:[ALAssetsFilter allPhotos]];
            if (group.numberOfAssets > 0)
            {
                [self.assetsGroups addObject:group];
                __block int i = 0;
                NSMutableArray* thumbnails = @[].mutableCopy;
                ALAssetsGroupEnumerationResultsBlock resultsBlock = ^(ALAsset *asset, NSUInteger index, BOOL *stop) {
                    if (asset) {
                        [thumbnails addObject:[UIImage imageWithCGImage:asset.thumbnail]];
                        i++;
                        if (i > 2) {
                            *stop = YES;
                        }
                    }
                };
                [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:resultsBlock];
                [self.groupThumbnails addObject:thumbnails];
            }
        }
        else
        {
            [self reloadData];
        }
    };
    
    
    ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
        
//        [self showNotAllowed];
        
    };
    
    // Enumerate Camera roll first
    [self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
                                      usingBlock:resultsBlock
                                    failureBlock:failureBlock];
    // Then PhotoStream
    [self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupPhotoStream
                                      usingBlock:resultsBlock
                                    failureBlock:failureBlock];

    // Then all other groups
    NSUInteger type = ALAssetsGroupLibrary | ALAssetsGroupAlbum | ALAssetsGroupEvent |
    ALAssetsGroupFaces;
    
    [self.assetsLibrary enumerateGroupsWithTypes:type
                                      usingBlock:resultsBlock
                                    failureBlock:failureBlock];
}

- (void)reloadData
{
//    if (self.assetsGroups.count == 0)
//        [self showNoAssets];
    
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHex:0xe8e8e8];
    self.tableView.backgroundColor = [UIColor colorWithHex:0xe8e8e8];
    [self setupGroup];
    self.title = NSLocalizedString(@"选择照片", @"");
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[JSPreviewManager sharedInstance] showPreView];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[JSPreviewManager sharedInstance] preview].delegateSelectImage = self;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[JSPreviewManager sharedInstance] preview].delegateSelectImage = nil;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.assetsGroups.count + 1;
//    return self.assetsGroups.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JSPhotoGroupCell* cell = [tableView dequeueReusableCellWithIdentifier:@"photoGroupCell"];
    if (0 == indexPath.row) {
        cell.name.text = NSLocalizedString(@"Camera360", @"");
        cell.count.text = @"360";
        //TODO 获取camera360相册的最后三张图片
//        [cell setThumbnails:@[[UIImage imageNamed:@"journey_1"], [UIImage imageNamed:@"journey_1"], [UIImage imageNamed:@"journey_1"]]];
    } else {
        ALAssetsGroup* group = [self.assetsGroups objectAtIndex:indexPath.row - 1];
        cell.name.text = [group valueForProperty:ALAssetsGroupPropertyName];
        cell.count.text = [NSString stringWithFormat:@"%ld", (long)group.numberOfAssets];
        [cell setThumbnails:[self.groupThumbnails objectAtIndex:indexPath.row - 1]];
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (0 == indexPath.row) {
        [self performSegueWithIdentifier:@"showPhotoChoose" sender:@[[[JSModelManager sharedInstance] getImageItem]]];
    } else {
        ALAssetsGroup* group = [self.assetsGroups objectAtIndex:indexPath.row - 1];
        [self performSegueWithIdentifier:@"showPhotoChoose" sender:group];
    }
//        ALAssetsGroup* group = [self.assetsGroups objectAtIndex:indexPath.row];
//        [self performSegueWithIdentifier:@"showPhotoChoose" sender:group];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"showPhotoChoose"]) {
        JSPhotoChooseViewController* controller = segue.destinationViewController;
        if ([sender isKindOfClass:[ALAssetsGroup class]]) {
            controller.group = sender;
            controller.type = E_ALBUM_SYS;
        } else if ([sender isKindOfClass:[NSArray class]]) {
            controller.assets = sender;
            controller.type = E_ALBUM_CAMER360;
        }
    } else if ([segue.identifier isEqualToString:@"showModelEdit0"]) {
        NSArray* imageAssets = sender;
        JSModelEditViewController* controller = segue.destinationViewController;
        controller.imageAssets = imageAssets;
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate

- (void)startPintuAction:(JSImageAddPreView *)sender
{
    NSArray* imageAssets = ((JSImageAddPreView *)sender).imageassets;
    if (imageAssets.count > 0) {
        [self performSegueWithIdentifier:@"showModelEdit0" sender:imageAssets];
    } else {
        //TODO alert 请选择图片
    }
}
@end
